import React, { useState, useEffect } from 'react';
import { Card, Space, Button, Divider, Typography, Skeleton, Empty } from 'antd';
import { useNavigate } from 'react-router-dom';

import { getCityList } from '@/api/city';
import { getCultPopList } from '@/api/cultruePop';
import { COLOR_THEME } from '@/config/theme';
import { urlMap, imagesMap } from '@/utils';
import './index.scss';
// import '@/config/font.css'

const { Meta } = Card;
/*
 * @Author: Eli.Chen
 * @Date: 2025-03-04 15:37:56
 * @LastEditors: Eli.Chen
 * @LastEditTime: 2025-03-20 10:27:23
 * @Description: 文化习俗科普
 */

export default function CultPop() {
    const [loading, setLoading] = useState(true);
    const [cities, setCities] = useState([]);
    const [selectedCity, setSelectedCity] = useState();
    const [cultureData, setCultureData] = useState([]);
    const navigate = useNavigate();

    useEffect(() => {
        const timer = setTimeout(() => setLoading(false), 1000);
        return () => clearTimeout(timer);
    }, [selectedCity]);

    useEffect(() => {
        const fetchCities = async () => {
            try {
                const citiesData = await getCityList();
                const { data: cityList } = citiesData;
                const sortedCities = [...cityList].sort((a, b) => {
                    if (a.cityName === '广州') return -1;
                    if (b.cityName === '广州') return 1;
                    return 0;
                });
                setCities(sortedCities);
                setSelectedCity(sortedCities[0] || null);
                setLoading(false);
            } catch (error) {
                setCities([]);
                setSelectedCity(null);
                setLoading(false);
            }
        };
        fetchCities();
    }, []);

    useEffect(() => {
        const fetchCulture = async () => {
            if (!selectedCity?.cityId) return;

            setLoading(true);
            const startTime = Date.now();
            try {
                const res = await getCultPopList(selectedCity.cityId);
                if (res.code === 200) {
                    setCultureData(res.data);
                }
            } catch (error) {
                console.error('文化数据加载失败:', error);
            } finally {
                const elapsed = Date.now() - startTime;
                const remaining = Math.max(500 - elapsed, 0);
                setTimeout(() => setLoading(false), remaining);
            }
        };
        fetchCulture();
    }, [selectedCity?.cityId]);

    return (
        <div
            className="cultPop-container"
            style={{
                backgroundColor: `${COLOR_THEME.BG_SECONDARY}`,
            }}
        >
            <Card className="cultPop-card">
                <Space direction="vertical">
                    <Space align="center">
                        <Typography
                            className="cultPop-title"
                            style={{
                                color: COLOR_THEME.TEXT_BASE,
                                whiteSpace: 'nowrap',
                                fontSize: '24px',
                                fontFamily: "'STXingkai', cursive",
                            }}
                        >
                            广东专区
                        </Typography>
                        <Space size={[8, 16]} wrap>
                            {cities.map((city) => (
                                <Button
                                    key={city.cityId}
                                    type={city.cityId === selectedCity?.cityId ? 'primary' : 'default'}
                                    onClick={() => setSelectedCity(city)}
                                >
                                    {city.cityName}
                                </Button>
                            ))}
                        </Space>
                    </Space>
                    <Divider />
                    <Space
                        size={[30, 16]}
                        wrap
                        style={{
                            width: '100%',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            flexWrap: 'wrap',
                        }}
                    >
                        <div
                            style={{
                                width: '99%',
                                display: 'flex',
                                justifyContent: 'center',
                                flexWrap: 'wrap',
                                gap: '16px',
                                margin: '0 auto',
                                gridGap: '16px',
                                gridAutoColumns: '1fr',
                            }}
                        >
                            {loading &&
                                Array.from({ length: 12 }).map((_, index) => (
                                    <div
                                        key={index}
                                        style={{
                                            width: 300,
                                            margin: '8px',
                                            flex: '0 0 calc(25% - 32px)',
                                        }}
                                    >
                                        <Skeleton active style={{ padding: 16 }} />
                                    </div>
                                ))}
                            {!loading && cultureData?.length > 0 ? (
                                cultureData.map((item) => {
                                    return (
                                        <Card
                                            key={item.id}
                                            hoverable
                                            style={{ width: 300, margin: '8px' }}
                                            cover={
                                                <img
                                                    alt={item?.title}
                                                    src={
                                                        urlMap.defaultUrl +
                                                        imagesMap.thridPicturePath +
                                                        item?.id +
                                                        '/' +
                                                        item?.coverImage
                                                    }
                                                    style={{ width: 300, height: 160, objectFit: 'cover' }}
                                                />
                                            }
                                            onClick={() => navigate('/cultPop/' + item.id)}
                                        >
                                            <Meta
                                                title={item.title}
                                                description={item.summary}
                                                style={{
                                                    display: 'flex',
                                                    justifyContent: 'center',
                                                    alignItems: 'center',
                                                    width: '100%',
                                                }}
                                            />
                                        </Card>
                                    );
                                })
                            ) : (
                                <Empty
                                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                                    description={
                                        <div
                                            style={{
                                                whiteSpace: 'nowrap',
                                            }}
                                        >
                                            暂无数据
                                        </div>
                                    }
                                />
                            )}
                        </div>
                    </Space>
                </Space>
            </Card>
        </div>
    );
}
